package com.njit.office.controller;

import com.njit.office.dataobject.LoginUser;
import com.njit.office.form.CreateTeamForm;
import com.njit.office.form.JoinTeamForm;
import com.njit.office.model.Result;
import com.njit.office.model.TeamModel;
import com.njit.office.service.TeamService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/teams/")
public class TeamController {

    @Resource
    TeamService teamService;

    @PostMapping("add")
    @ResponseBody
    public Result createTeam(@ModelAttribute("createTeamForm") CreateTeamForm form){
        return teamService.createTeam(form.getUserId(), form.getTeamName());
    }

    @PostMapping("join")
    @ResponseBody
    public Result joinTeam(@ModelAttribute("joinTeamForm") JoinTeamForm form){
        return teamService.joinTeam(form.getUserId(), form.getInviteCode());
    }

    @GetMapping("updateView/joined")
    public String updateJoinedTeams(Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session == null || session.getAttribute("userId") == null) {
            return "team::joinedTeamsFragment";
        }
        String userId = (String) session.getAttribute("userId");
        Result res1 = teamService.getJoinedTeams(userId);
        model.addAttribute("joinedTeams", res1.getData());
        return "team::joinedTeamsFragment";
    }

    @GetMapping("updateView/created")
    public String updateCreatedTeams(Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session == null || session.getAttribute("userId") == null) {
            return "team::createdTeamsFragment";
        }
        String userId = (String) session.getAttribute("userId");
        Result res1 = teamService.getCreatedTeams(userId);
        model.addAttribute("createdTeams", res1.getData());
        return "team::createdTeamsFragment";
    }


//    dasda
    @DeleteMapping("/{teamId}")
    public Result deleteTeam(@PathVariable("teamId") String teamId, @PathParam("userId")String userId) {

        return teamService.dismissTeam(userId, teamId);
    }

    @PostMapping("/member")
    public Result joinTeam(@RequestBody Map<String, String> map) {
        String userId = map.get("userId");
        String inviteCode = map.get("inviteCode");
        return teamService.joinTeam(userId, inviteCode);
    }



    @GetMapping("/created")
    public Result getMyCreatedTeam(@PathParam("userId")String userId){

        return teamService.getCreatedTeams(userId);
    }

}
